package example

import (
	"gitee.com/Luna-CY/Golang-Project-Template/entry/http/request"
	"gitee.com/Luna-CY/Golang-Project-Template/entry/http/response"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/context/contextutil"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/i18n"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/interface/dao"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/util/pointer"
	"gitee.com/Luna-CY/Golang-Project-Template/model"
	"github.com/gin-gonic/gin"
)

type ListRequest struct {
	request.BaseListRequest

	Field4 int `json:"field4" validate:"optional" enums:"0,1,2,3" binding:"omitempty,oneof=0 1 2 3"` // filter by field4, enums: 0 - All, 1 - A, 2 - B, 3 - C
}

type ListItem struct {
	Id     string `json:"id" validate:"required"`                 // 数据ID
	Name   string `json:"name" validate:"required"`               // 字符串字段
	Value  uint64 `json:"value" validate:"required"`              // 数值字段
	Enable bool   `json:"enable" validate:"required"`             // 布尔字段
	Type   int    `json:"type" validate:"required" enums:"1,2,3"` // 枚举字段, enums: 1 - A, 2 - B, 3 - C
}

// List List Example
// @tags category/example
// @summary list for data
// @param param body ListRequest true "request body"
// @success 200 {object} response.Response{data=response.BaseDataList[ListItem]{}} "successful. click to expand response structure"
// @router /example/list [post]
func (cls *Example) List(c *gin.Context) (response.Code, any, errors.I18nError) {
	var body = ListRequest{BaseListRequest: request.BaseListRequest{Page: 1, Size: 20}}
	if err := request.ShouldBindJSON(c, &body); nil != err {
		return response.InvalidParams, nil, errors.NewI18n(i18n.CommonIdInvalidRequest, err.Relation(errors.ErrorInvalidRequest("SHGWHE_LE.E_LE.L_ST.373016", "参数错误")))
	}

	var options = []dao.BusinessExampleOption{dao.BusinessExampleOptionWithOrderDefault()}
	if 0 != body.Field4 {
		options = append(options, dao.BusinessExampleOptionWithField4(model.BusinessExampleEnumFieldType(body.Field4)))
	}

	// create context with gin context
	// not allow use gin context in internal service
	var ctx = contextutil.NewContextWithGin(c)

	// search data
	total, data, err := cls.example.ListExampleByCondition(ctx, body.Page, body.Size, options...)
	if nil != err {
		return response.ServerInternalError, nil, errors.NewI18n(i18n.CommonIdServerInternalError, err.Relation(errors.ErrorServerInternalError("SHGWHE_LE.E_LE.L_ST.523027", "获取数据失败")))
	}

	// response data
	var res = pointer.Default(response.BaseDataList[ListItem]{Total: total, Page: body.Page, Size: body.Size})
	for _, example := range data {
		var item = ListItem{
			Id:     example.Id,
			Name:   *example.Name,
			Value:  *example.Value,
			Enable: *example.Enable,
			Type:   int(*example.Type),
		}

		res.Data = append(res.Data, item)
	}

	return response.Ok, res, nil
}
